package public

import (
	"MoSkeleton/config/consts"
	fc "MoSkeleton/framework/core/consts"
	"MoSkeleton/framework/core/dto/response"
	"MoSkeleton/framework/core/motypes"
	"MoSkeleton/framework/utils"
	"MoSkeleton/global"
	"MoSkeleton/services"
	"MoSkeleton/web/pogos/request/public"
	public2 "MoSkeleton/web/pogos/response/public"
	system3 "MoSkeleton/web/pogos/response/system"
	"github.com/gin-gonic/gin"
	"github.com/mssola/user_agent"
	"go.uber.org/zap"
	"time"
)

type AuthCtrl struct {
}

// Login
// @Tags 公共
// @Summary 登录
// @Description 登录
// @Accept application/json
// @Produce   application/json
// @Router /public/login [post]
// @Success   200   {object}  response.Response{data=object,msg=string}  "登录成功""
// @Param data body public.LoginReq true "登录参数"
func (a *AuthCtrl) Login(c *gin.Context) {
	model, exists := c.Get(fc.GinContext_Model_Key)
	var loginReq public.LoginReq
	ok := false
	if exists {
		if loginReq, ok = model.(public.LoginReq); !ok {
			response.FailMsgAsI18n(c, fc.ValidatorParamsCheckFailCode, fc.TKey_ValidatorParamsCheckFailMsg)
			return
		}
	} else {
		if err := c.ShouldBindJSON(&loginReq); err != nil {
			response.ValidatorError(c, err)
			return
		}
	}

	onlineUser := system3.OnlineUserResp{}
	onlineUser.LoginTime = &motypes.MoTime{Time: time.Now()}
	a.onlineUserInfoFromGin(c, &onlineUser)

	tokenStr, err := services.ServiceGroupInst.PublicGroupInst.AuthServiceInst.Login(loginReq, &onlineUser)
	if err != nil {
		global.MoLogger.Error("登录失败", zap.Error(err))
		response.FailMsgAsI18n(c, fc.CommLoginFailCode, fc.TKey_CommLoginFailMsg)
		return
	}
	//for log
	c.Set(fc.GinContext_LoginState_Key, consts.U_YES)
	response.SuccessAsI18n(c, fc.TKey_CommLoginSuccessMsg, public2.TokenResp{Token: tokenStr})
}

func (a *AuthCtrl) onlineUserInfoFromGin(c *gin.Context, onlineUser *system3.OnlineUserResp) {
	onlineUser.Ipaddr = utils.GetRequestIp(c)
	ua := user_agent.New(c.GetHeader("User-Agent"))
	onlineUser.Os = ua.OS()
	onlineUser.Browser, _ = ua.Browser()
}
